<!--
* @description 支持画框功能的图片预览
* @author zywu
* @date 2021/01/13 10:16:55
!-->
<template>
  <div>
    <el-image-viewer
      v-if="showViewer"
      ref="myViewer"
      :on-close="closeViewer"
      :url-list="srcList"
      :on-switch="switchPic"
      :z-index="3999"
    />
    <trans-ai-pic
      v-if="showCanvasPreview"
      :transAiPicToBase64="transAiPicToBase64"
      :drawData="drawData"
      :appendToBody="false"
    />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import TransAiPic from '@/components/TransAiPic' // 视频分析图片转base64
var loading
export default {
  props: {
    originList: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      showViewer: false,
      viewerIndex: 0, // 正在预览哪张图片
      drawData: {}, // 图片对象
      showCanvasPreview: false, // 图片对象转base64的组件
      srcList: [],
    }
  },

  components: {
    ElImageViewer,
    TransAiPic,
  },

  computed: {},

  watch: {
    originList(val, oldVal) {
      if (JSON.stringify(val) !== JSON.stringify(oldVal)) {
        this.srcList = this.originList.map((n) => {
          return n.pic
        })
      }
    },
  },

  created() {
    this.srcList = this.originList.map((n) => {
      return n.pic
    })
  },

  mounted() {},

  methods: {
    switchPic(index) {
      this.viewerIndex = index
      let picObjData = this.originList[index]
      let currentPic = this.srcList[index]
      // 需要转码成Base64的
      if (!currentPic.startsWith('data:image/') && picObjData.resultRegion) {
        if (typeof picObjData.resultRegion === 'object') {
          picObjData.resultRegion = JSON.stringify(picObjData.resultRegion)
        }
        this.loading()
        this.drawData = picObjData
        this.showCanvasPreview = true
      } else {
        // 图片已经是Base64或者无需画框
        this.$set(this.srcList, this.viewerIndex, currentPic)
        this.showViewer = true
        // 设置当前查看的图片索引
        this.$nextTick(() => {
          this.$refs.myViewer.index = +this.viewerIndex
        })
      }
    },
    closeViewer() {
      this.showViewer = false
    },
    transAiPicToBase64(base64Data) {
      if (base64Data) {
        this.$set(this.srcList, this.viewerIndex, base64Data)
      }
      this.showViewer = true
      // 设置当前查看的图片索引
      this.$nextTick(() => {
        this.$refs.myViewer.index = +this.viewerIndex
      })
      this.showCanvasPreview = false
      loading && loading.close()
    },
    loading() {
      loading = this.$loading({
        lock: true,
        text: '正在加载图片',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        loading && loading.close()
      }, 3000)
    },
  },
}
</script>
<style lang='scss'>
</style>